//
//  LayerView.m
//  ActivityParser
//
//  Created by Alejandro Uño on 7/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LayerView.h"
#import "JSONKit.h"

#define kTagOpenButton	100
#define kTagInFile		kTagOpenButton+1		
#define kTagSaveButton	kTagInFile+1
#define kTagOutFile		kTagSaveButton+1


@implementation LayerView

+(LayerView*) create
{
	return [[[self alloc] init] autorelease];
}

- (id) init
{
	if (self = [super init]) 
	{
		NSLog(@"LayerView::init....");
		
		NSTextField *title = [[NSTextField alloc] initWithFrame:CGRectMake(100, 550, 650, 25)];
        [title setStringValue:@"Selecciona el archivo JSON con la actividad a convertir..."];
        [title setEditable:NO];
        [self addSubview:title];
        
        NSButton *button = [[NSButton alloc] initWithFrame:CGRectMake(150, 500, 80, 25)];
		[button setTitle:@"Pincha Acá!"];
		[button setTarget:self];
		[button setTag:kTagOpenButton];
		[button setAction:@selector(buttonPressed)];
	
		[self addSubview:button];
		
		NSTextField *text = [[NSTextField alloc] initWithFrame:CGRectMake(50, 425, 650, 25)];
		[text setEditable:NO];
		[text setTag:kTagInFile];
		
		[self addSubview:text];
        
	}
	return self;
}

- (void) buttonPressed
{
	NSLog(@"LayerView::buttonPressed...");
	int i;
	// Create the File Open Dialog class.
	NSOpenPanel* openDlg = [NSOpenPanel openPanel];
	
	// Enable the selection of files in the dialog.
	[openDlg setCanChooseFiles:NO];
	// Multiple files not allowed
	[openDlg setAllowsMultipleSelection:NO];
	// Can't select a directory
	[openDlg setCanChooseDirectories:YES];
	
	// Display the dialog. If the OK button was pressed,
	// process the files.
	if ( [openDlg runModal] == NSOKButton )
	{
		// Loop through all the files and process them.
		for( i = 0; i < [[openDlg URLs] count]; i++ )
		{
			NSURL* directoryURL = [openDlg URLs][i];
			
			NSTextField *textFile = [self viewWithTag:kTagInFile];
			
			NSString *directoryName = directoryURL.path;
			
			[textFile setStringValue:directoryName];
            
			NSLog(@"Directory name: %@", directoryName);

            NSFileManager *manager = [NSFileManager defaultManager];
            
            NSError *error;
            
			for (NSString *fileName in [manager contentsOfDirectoryAtPath:directoryURL.path error:&error])
            {
                NSLog(@"File name: %@", fileName);
                NSString *filePath = [directoryURL.path stringByAppendingPathComponent:fileName];
                NSLog(@"File path: %@", filePath);
                
                NSString *JSONString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
            
//                NSDictionary *JSONdict = [JSONString mutableObjectFromJSONString];
//                NSMutableDictionary * tmpBook = [NSMutableDictionary dictionaryWithDictionary:JSONdict];
                NSMutableDictionary * tmpBook = [JSONString mutableObjectFromJSONString];
                
                BOOL writeToFile = NO;
                
                if (tmpBook[@"pages"]!=nil)
                {
                    NSLog(@"es un book");
                    for (NSMutableDictionary* pageDict in tmpBook[@"pages"])
                    {
                        writeToFile = [self tryParseJSONDict:pageDict];
                    }
                    
                }
                else if (tmpBook[@"activities"]!=nil)
                {
                    writeToFile = [self tryParseJSONDict:tmpBook];
                }
                else
                {
                    NSLog(@"error parseando objeto que no es book ni pagina-----> es include????");
                }
                
                if (writeToFile)
                {
                    [self saveJSONDict:tmpBook toFile:fileName inDirectory:directoryName];
                }
            }
		}
	}
}

- (BOOL) tryParseJSONDict:(NSMutableDictionary*) pageDict
{
    BOOL writeToFile = NO;
    
    if ([pageDict[@"activities"] count]>0)
    {
        NSLog(@"pagina con actividades");
        NSMutableArray *tmpArray = [NSMutableArray array];

		for (NSDictionary* activityData in pageDict[@"activities"])
		{
			NSLog(@"LayerView::Encontre una actividad...");
			NSMutableDictionary *newActivityData = (NSMutableDictionary*)[self createNewActivityDataWithDict:activityData];
			tmpArray[0] = newActivityData;
		}
        pageDict[@"activities"] = tmpArray;
        
        writeToFile = YES;
    }
    else
    {
        NSLog(@"pagina sin actividades");
    }
    return writeToFile;
}

- (void) saveJSONDict:(NSDictionary*)book toFile:(NSString*)fileName inDirectory:(NSString*)directoryName
{
    NSError *error2;
    NSString *fileNameWithSuffix =[NSString stringWithFormat:@"NEW-%@", fileName ,nil];
    NSString *fruta = [directoryName stringByAppendingPathComponent:fileNameWithSuffix];
    
    [[book JSONPrettyString] writeToFile:fruta atomically:NO encoding:NSUTF8StringEncoding error:&error2];
}

- (void) parseJSON:(NSURL*) JSONurl
{
	@try
	{
		NSError * error=nil;
		NSMutableString * JSONString = [NSMutableString stringWithContentsOfFile:JSONurl.path encoding:NSUTF8StringEncoding error:&error];
		
		NSLog(@"Error??? %@", error.description);
		
		NSDictionary *book = [JSONString objectFromJSONString]; 
		NSMutableDictionary * tmpBook = [NSMutableDictionary dictionaryWithDictionary:book];
		
		for (NSDictionary* activityData in tmpBook[@"activities"])
		{
			NSLog(@"LayerView::Encontre una actividad...");
			
			NSDictionary *newActivityData = [self createNewActivityDataWithDict:activityData];	

			NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:tmpBook[@"activities"]];
			
			tmpArray[0] = newActivityData;
			
			tmpBook[@"activities"] = tmpArray;
		}
		
		NSError *error2;
        NSString *fileNameWithSuffix =[NSString stringWithFormat:@"NEW-%@", JSONurl.lastPathComponent ,nil];
		NSString *fruta = [[JSONurl.path stringByDeletingLastPathComponent] stringByAppendingPathComponent:fileNameWithSuffix];
		
		[[tmpBook JSONPrettyString] writeToFile:fruta atomically:NO encoding:NSUTF8StringEncoding error:&error2];

		NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(50, 100, 500, 300)];
		[scrollView setBorderType:NSNoBorder];
		[scrollView setHasVerticalScroller:YES];
		[scrollView setHasHorizontalScroller:NO];
		[scrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];		
		
		NSTextView *textView = [[NSTextView alloc] initWithFrame:CGRectMake(50, 100, 500, 300)];
		[textView setString:[tmpBook JSONPrettyString]];
		[textView setEditable:NO];
		[textView setVerticallyResizable:YES];
		
		[scrollView setDocumentView:textView];		
		
		[self addSubview:scrollView];	
	}
	@catch (NSException *exception) 
	{
		NSAlert *alert = [NSAlert alertWithMessageText:exception.description defaultButton:@"YES" alternateButton:@"NO" otherButton:nil informativeTextWithFormat:nil];	
		[alert runModal];
	}
	@finally 
	{
		NSLog(@"Al horno");
	}	
}

- (NSDictionary*) createNewActivityDataWithDict:(NSDictionary*) activityDict
{
    if([[activityDict[@"type"] uppercaseString] isEqualToString:@"QUIZ"])
    {
        return [self createQuizActivityDataWithDict:activityDict];
    }
    else if([[activityDict[@"type"] uppercaseString] isEqualToString:@"MEMOTEST"])
    {
        return [self createMemoTestActivityDataWithDict:activityDict];
    }
    else if([[activityDict[@"type"] uppercaseString] isEqualToString:@"PUZZLE"])
    {
        return [self createPuzzleActivityDataWithDict:activityDict];
    }
    
    return nil;
}

- (NSDictionary*) createPuzzleActivityDataWithDict:(NSDictionary*) activityDict
{
	NSMutableDictionary *resDict=[[NSMutableDictionary alloc] init];
	
    // INIT PUZZLE HEADER
    resDict[@"type"]        = @"STATE";
    resDict[@"icon"]        = activityDict[@"icon"];
    resDict[@"name"]        = [activityDict[@"type"] uppercaseString];
    
	NSMutableArray      *states    = [[[NSMutableArray alloc] init] autorelease];
	NSMutableDictionary *stateDict = [[[NSMutableDictionary alloc] init] autorelease];
    
	stateDict[@"idState"]   = [activityDict[@"type"] uppercaseString];
	stateDict[@"title"]     = activityDict[@"title"];
//	stateDict[@"offset"]    = activityDict[@"offset"];
	stateDict[@"reference"] = activityDict[@"reference"];
	stateDict[@"tolerance"] = activityDict[@"tolerance"];
	stateDict[@"piecesScale"] = activityDict[@"piecesScale"];
	stateDict[@"positions"] = activityDict[@"positions"];
	stateDict[@"pieces"]    = activityDict[@"pieces"];
	
    [states addObject:stateDict];
    
    resDict[@"states"]      = states;
	
    // END PUZZLE HEADER
	
	return [resDict autorelease];
}

- (NSDictionary*) createMemoTestActivityDataWithDict:(NSDictionary*) activityDict
{
	NSMutableDictionary *resDict=[[NSMutableDictionary alloc] init];
	
    // INIT MEMOTEST HEADER
    resDict[@"type"]          = @"STATE";
    resDict[@"showInHud"]     = activityDict[@"showInHud"];
    resDict[@"name"]          = [activityDict[@"type"] uppercaseString];
    
	NSMutableArray      *states    = [[[NSMutableArray alloc] init] autorelease];
	NSMutableDictionary *stateDict = [[[NSMutableDictionary alloc] init] autorelease];
    
	stateDict[@"idState"]   = [activityDict[@"type"] uppercaseString];
	stateDict[@"title"]     = activityDict[@"title"];
    
	NSMutableArray *cards	= [[[NSMutableArray alloc] init] autorelease];
	
	for (NSDictionary* oldCardData in activityDict[@"cards"])
    {
		NSMutableDictionary *newCardData = [[NSMutableDictionary alloc] init];
        
		newCardData[@"id"]            = oldCardData[@"id"];
        newCardData[@"normalImage"]   = oldCardData[@"card_background"];
        newCardData[@"selectedImage"] = activityDict[@"image"];
		newCardData[@"matches"]       = oldCardData[@"matches"];
        
		[cards addObject:newCardData];
    }
    
    stateDict[@"cards"]     = cards;
    stateDict[@"positions"] = activityDict[@"positions"];
    
    [states addObject:stateDict];
    
    resDict[@"states"]      = states;
	
    // END MEMOTEST HEADER
	
	return [resDict autorelease];
}

- (NSDictionary*) createQuizActivityDataWithDict:(NSDictionary*) activityDict
{
	NSMutableDictionary *resDict=[[NSMutableDictionary alloc] init];
	
    // INIT QUIZ HEADER
    resDict[@"type"]          = @"STATE";
    resDict[@"showInHud"]     = activityDict[@"showInHud"];
    resDict[@"behavior"]      = activityDict[@"behavior"];
    resDict[@"hud_button"]    = activityDict[@"hud_button"];
    resDict[@"spread_button"] = activityDict[@"spread_button"];
    resDict[@"icon"]          = activityDict[@"icon"];
    resDict[@"name"]          = [activityDict[@"type"] uppercaseString];
    
	NSMutableArray *states = [[[NSMutableArray alloc] init] autorelease];
    
	NSMutableDictionary *stateDict = [[[NSMutableDictionary alloc] init] autorelease];
    
	stateDict[@"idState"] = [activityDict[@"type"] uppercaseString];
	stateDict[@"fonts"]   = activityDict[@"fonts"];
    stateDict[@"title"]   = activityDict[@"title"];
    
	NSMutableArray *questions	= [[[NSMutableArray alloc] init] autorelease];
	NSMutableArray *answers		= [[[NSMutableArray alloc] init] autorelease];
	
	NSUInteger questionsCount = 0;
	
	for (NSDictionary* oldQuestionData in activityDict[@"questions"])
	{
		NSMutableDictionary *currentQuestionDict = [[NSMutableDictionary alloc] init];
        
		currentQuestionDict[@"id"]       = [NSString stringWithFormat:@"%lu",questionsCount+1];
        currentQuestionDict[@"image"]    = oldQuestionData[@"question"][@"image"];
		currentQuestionDict[@"position"] = oldQuestionData[@"question"][@"desiredPosition"];
        
		[questions addObject:currentQuestionDict];
		
		questionsCount++;
        
		NSMutableArray *currentAnswers = [[[NSMutableArray alloc] init] autorelease];
		NSUInteger answersCount = 0;
		
		for (NSDictionary* oldAnswerData in oldQuestionData[@"answers"])
		{
			NSMutableDictionary *currentAnswerDict = [[NSMutableDictionary alloc] init];
            
			currentAnswerDict[@"id"]          = [NSString stringWithFormat:@"%lu",answersCount+1];
			currentAnswerDict[@"isCorrect"]   = [oldAnswerData[@"correct"] uppercaseString];
			currentAnswerDict[@"normalImage"] = oldAnswerData[@"image"];
			currentAnswerDict[@"position"]    = @{@"x":oldAnswerData[@"position"][@"x"],@"y":oldAnswerData[@"position"][@"y"]};
            
			[currentAnswers addObject:currentAnswerDict];
			answersCount++;
		}
		
		[answers addObject:currentAnswers];
	}
    
    stateDict[@"questions"]     = questions;
    stateDict[@"answers"]       = answers;
    stateDict[@"roundsCount"]   = [NSString stringWithFormat:@"%lu",questionsCount];
    
	[states addObject:stateDict];
	
    resDict[@"states"] = states;
	
    // END QUIZ HEADER
	
	return [resDict autorelease];
}

- (void) dealloc
{
	NSLog(@"LayerView::dealloc...");
	[super dealloc];
}

@end
